package com.shadow.cloud.security.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shadow.cloud.security.entity.UserEntity;
import com.shadow.cloud.security.entity.rel.RelUserOrgEntity;
import com.shadow.cloud.security.mapper.UserMapper;
import com.shadow.cloud.security.mapper.rel.RelUserOrgMapper;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@AllArgsConstructor
@Service
public class UserService extends ServiceImpl<UserMapper, UserEntity> implements IService<UserEntity> {

    private final UserMapper userMapper;
    private final RelUserOrgMapper relUserOrgMapper;

    public List<UserEntity> getUserList(final String orgId) {
        if (StringUtils.isBlank(orgId)) {
            return Collections.emptyList();
        }
        LambdaQueryWrapper<RelUserOrgEntity> queryWrapper = new LambdaQueryWrapper<RelUserOrgEntity>()
                .eq(RelUserOrgEntity::getOrgId, orgId);
        List<RelUserOrgEntity> relUserOrgEntityList = relUserOrgMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(relUserOrgEntityList)) {
            return Collections.emptyList();
        }
        List<String> userIdList = relUserOrgEntityList.stream()
                .map(RelUserOrgEntity::getUserId)
                .collect(Collectors.toList());
        return userMapper.selectBatchIds(userIdList);
    }

    public UserEntity selectByAccount(final String account) {
        if (StringUtils.isBlank(account)) {
            return null;
        }
        LambdaQueryWrapper<UserEntity> wrapper = new LambdaQueryWrapper<UserEntity>()
                .eq(UserEntity::getAccount, account)
                .last("limit 1");
        return userMapper.selectOne(wrapper);
    }

    public List<String> selectUserPermissions(final String userId) {
        return userMapper.selectUserPermissions(userId);
    }
}
